package com.winit.core.server;

import com.winit.core.server.base.ExecResultHandler;
import com.winit.core.server.linux.LinuxSSHServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * Created by wangjian on 16/10/17.
 */
public class Server extends LinuxSSHServer {

    private static Logger logger = LoggerFactory.getLogger(Server.class);

    public ExecResultHandler handler = new ExecResultHandler();

    public Server(String ip, String userName, Integer port) throws Exception {
        super(ip, userName, port);
    }

    //判断路径是否存在 不存在 且 isCreate=true时 创建
    public void isPathExist(String path,boolean isCreate,boolean useRoot) throws Exception{
        if(StringUtils.isEmpty(path)){
            logger.error("Server:判断路径是否存在,path为空.");
            throw new Exception("判断路径是否存在,path为空");
        }
        this.initHandler();
        this.doExec(this.handler,"ls "+path);
        if(!StringUtils.isEmpty(this.handler.getMessage())
                && this.handler.getMessage().indexOf("No such file or directory") != -1){
            if(isCreate){
                this.initHandler();
                if(useRoot){
                    this.doExec(this.handler,"source /etc/profile && sudo mkdir -p "+path+" && sudo chown -R beetle.beetle "+path);
                }else {
                    this.doExec(this.handler,"mkdir -p "+path);
                }
                if(!StringUtils.isEmpty(this.handler.getMessage())
                        && (this.handler.getMessage().indexOf("Permission denied") != -1
                        || this.handler.getMessage().indexOf("sudo") != -1)){
                    throw new Exception("目录不存在,且创建失败,path="+path+",msg="+this.handler.getMessage());
                }
            }else {
                throw new Exception("文件不存在.path="+path);
            }
        }
    }

    /**
     * 获取当前机器空间使用率
     * @return
     */
    public String getPercentOfSpace() throws Exception{
        this.initHandler();
        this.doExec(this.handler,"df -Ph / |awk 'NR==2{print $5}'");
        return this.handler.getMessage().replace("%","");
    }

    public void initHandler(){
        this.handler = new ExecResultHandler();
    }
}
